import pypdf
import os, sys
pageNum, secNum, figNum = sys.argv[1].split(',')
crop_box = [float(i) for i in sys.argv[2].split(',')]
inputName = 'origin.pdf'
interName = "temp.pdf"
figNum = f"p{pageNum}" if figNum == "0" else figNum
figName = f"fig_{secNum}_{figNum}.pdf"
input_pdf = pypdf.PdfReader(open(inputName, 'rb'))
output_pdf = pypdf.PdfWriter()
page = input_pdf.pages[int(pageNum)-1]
height = page.mediabox.top
page.mediabox.left = crop_box[0]
page.mediabox.right = crop_box[1]
page.mediabox.top = height - crop_box[2]
page.mediabox.bottom = height - crop_box[3]
output_pdf.add_page(page)
with open(interName, 'wb') as output_file:
    output_pdf.write(output_file)
os.system(f"pdfcrop --margins \"0 0 0 0\" {interName} figures/{figName}")
print(f"finished. Figure name: {figName}")
